/* 
 * File:   ThreadBatchMerge.cpp
 * Author: Morpheus
 * 
 * Created on 24 juin 2013, 00:07
 */

#include <QtGui/qtextdocument.h>
#include <QtGui/qtextcursor.h>
#include <QtGui/qtextdocumentfragment.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qdir.h>
#include <QtPrintSupport/qprinter.h>
#include <QtGui/qimagewriter.h>
#include <QtGui/qtextdocumentwriter.h>
#include <QtGui/qpainter.h>
#include <QtSvg/QSvgGenerator>
#include <QtCore/qbytearray.h>
#include <QtCore/qmargins.h>

#include "ThreadBatchMerge.h"
#include "MyBatchMerge.h"

ThreadBatchMerge::ThreadBatchMerge(const QByteArray& array, const MyBatchSettingPrint& settingPrint, QObject* parent)
 : QThread(parent), m_array(array), m_settingPrint(settingPrint) {
}

ThreadBatchMerge::~ThreadBatchMerge() {
}

void ThreadBatchMerge::run(){
    QList<MyBatchMerge> batches;
    emit description(trUtf8("Initialisation"));
    {
        QDataStream in(m_array);
        in >> batches;
    }
    
    int count = batches.size();
    foreach(MyBatchMerge batch, batches){
        count+= batch.getBatchList().size();
    }
    
    emit range(0, count);
    emit progress(0);
    count = 0;
    QStringList imageWritersupportedFormat;
    QStringList textDocumentWritersupportedFormat;
    foreach(QByteArray fmtText, QTextDocumentWriter::supportedDocumentFormats()){
        textDocumentWritersupportedFormat << QString::fromLatin1(fmtText).toLower();
    }
    foreach(QByteArray fmtImg, QImageWriter::supportedImageFormats()){
        imageWritersupportedFormat << QString::fromLatin1(fmtImg).toLower();
    }
    
    for (int batchCount = 0; batchCount < batches.size(); batchCount++) {
        MyBatchMerge batch = batches.at(batchCount);
        if(!batch.isSaveFileOk()){
            emit description(tr("La description du chemin de sauvegarde du Batch %1 est invalide").arg(batch.getName()));
            sleep(1);
            emit progress(count += (batch.getBatchList().size()+1));
            continue;
        }
        QTextDocument* document = new QTextDocument();
        QTextCursor tCursor(document);
        bool bOk = true;
        for (int unitCount = 0; unitCount < batch.getBatchList().size(); unitCount++) {
            emit progress(++count);
            MyBatchUnit unit = batch.getBatchList().at(unitCount);
            tCursor.movePosition(QTextCursor::End);
            if(!unit.isFile()){
                emit description(tr("Batch %1 : Interpretation du Script %2").arg(batch.getName()).arg(unit.getContentText()));
//                sleep(1);
                QString tag = batch.interpretPatern(unit.getContentText() ,bOk);
                if(!bOk){
                    emit description(tr("Batch %1 : Le Script %2 à rencontrer une erreur").arg(batch.getName()).arg(unit.getContentText()));
                    sleep(2);
                    break;
                }
                tCursor.insertText(tag);
            }else{
                emit description(tr("Batch %1 : Ouverture du Fichier '%2'").arg(batch.getName()).arg(unit.getFilePath()));
//                sleep(1);
                QTextDocumentFragment frag(unit.document());
                tCursor.insertFragment(frag);
            }
        }
        emit progress(++count);
        if(bOk){
            // sauver le document
            QFileInfo info(batch.getSaveFile());
            QString fmt = batch.getSaveFileFormat().toLower();
            info.dir().mkpath(info.absolutePath());
            
            emit description(tr("Sauvegarde %1 du Batch %2 dans '%3'").arg(fmt.toUpper()).arg(batch.getName()).arg(info.absolutePath()));
            QPrinter printer;
            printer.setColorMode( static_cast<QPrinter::ColorMode>(m_settingPrint.getColor()) );
            printer.setFullPage( true );
            printer.setPaperSize( static_cast<QPrinter::PageSize>(m_settingPrint.getPaperSize()) );
            printer.setDocName( info.fileName() );
            printer.setResolution( m_settingPrint.getResolution() );
//            printer.setMargins(QMargins(m_settingPrint.getMargingLeft(), m_settingPrint.getMargingTop(), m_settingPrint.getMargingRight(), m_settingPrint.getMargingBottom()));
            
            const double mmToInch = 1.0 / 25.4;
            const QSizeF size = (document->size() * mmToInch * 10. * mmToInch * m_settingPrint.getResolution());
            QRectF documentRect(0.0, 0.0, size.width(), size.height());
            
            if(fmt == "pdf"){
                printer.setOutputFileName(info.absoluteFilePath());
                printer.setOutputFormat(QPrinter::PdfFormat);

                document->print(&printer);
            }else if(fmt == "svg"){
                QSvgGenerator generator;
                generator.setTitle( info.fileName() );
                generator.setFileName( info.absoluteFilePath() );
                generator.setResolution( m_settingPrint.getResolution() );
                generator.setViewBox( documentRect );

                QPainter painter( &generator );
                
                document->drawContents(&painter, documentRect );
            }else if(fmt == "ps"){
                printer.setOutputFileName(info.absoluteFilePath());
                printer.setOutputFormat( QPrinter::NativeFormat );

                QPainter painter( &printer );
                document->drawContents(&painter, documentRect );
                
            }else if(imageWritersupportedFormat.contains(fmt.toLatin1())){
                const QRect imageRect = documentRect.toRect();
                const int dotsPerMeter = qRound( m_settingPrint.getResolution() * mmToInch * 1000.0 );

                QImage image( imageRect.size(), QImage::Format_ARGB32 );
                image.setDotsPerMeterX( dotsPerMeter );
                image.setDotsPerMeterY( dotsPerMeter );
                image.fill( QColor( Qt::white ).rgb() );

                QPainter painter( &image );
                document->drawContents(&painter, imageRect );
//                painter.end();

                image.save( info.absoluteFilePath(), fmt.toLatin1() );
            }else if(textDocumentWritersupportedFormat.contains(fmt)){
                QTextDocumentWriter writer;
                writer.setFileName(info.absoluteFilePath());
                writer.setFormat(fmt.toLatin1());
                writer.write(document);
            }else{
                emit description(tr("Impossible Sauvegarde %1 du Batch %2 dans '%3'\n"
                "Format inconnu").arg(fmt.toUpper()).arg(batch.getName()).arg(info.absolutePath()));
                sleep(1);
                bOk = false;
            }
            if(bOk){
                emit batchUuidDoSuccess(batch.getUUID());
            }
        }
        document->deleteLater();
    }
    
    emit information(tr("OK"));
}

